using System;
using System.Collections.Generic;
using System.Text;
using Emlyn.Common.Tools.LayerInterfaces;
using System.Data;

namespace Emlyn.Common.Tools.BusinessLayer
{
    public abstract class BaseQuery<T, TKey, TDataLayer>
        where TDataLayer : IBaseDataLayer<T, TKey>
        where T: BaseItem
    {
        protected abstract T ConstructInstanceFromRow(DataRow lrow);
        
        protected TDataLayer _dl = default(TDataLayer);

        public BaseQuery(TDataLayer adl)
        {
            if (adl == null)
                throw new ArgumentNullException("adl");

            _dl = adl;
        }

        protected IList<T> ConstructInstancesFromDataSet(DataSet aDataset)
        {
            IList<T> retval = new List<T>();

            foreach (DataRow lrow in aDataset.Tables[0].Rows)
            {
                T lInstance = ConstructInstanceFromRow(lrow);
                lInstance.IsNew = false;
                retval.Add(lInstance);
            }

            return retval;
        }

        protected T ConstructInstanceFromDataSet(DataSet aDataSet)
        {
            IList<T> linstances = ConstructInstancesFromDataSet(aDataSet);

            T retval = default(T);

            if (linstances.Count > 0)
            {
                retval = linstances[0];
            }

            return retval;
        }

        public IList<T> SelectAll()
        {
            return ConstructInstancesFromDataSet(_dl.SelectAll());
        }

        public T Select(TKey aKey)
        {
            return ConstructInstanceFromDataSet(_dl.Select(aKey));
        }
    }
}
